﻿using DX.Security;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;

namespace Tools.Plugins.Auths
{
    class DefaultAuthService : IAuthService
    {

        public DefaultAuthService(IOptions<AuthOption> options, IAuthProvider authProvider, ILogger<DefaultAuthService> logger)
        {

            this.authProvider = authProvider;
            this.logger = logger;
            this.option = options.Value;
        }

        private readonly IAuthProvider authProvider;
        private readonly ILogger logger;
        private readonly AuthOption option;

        public void ChangePassword(string account, string oldpassword, string newpassword)
        {
            throw new NotSupportedException();
            /*
            try
            {
                authProvider.ChangePassword(account, oldpassword, newpassword);
            }
            catch (AuthException)
            {

                throw;
            }
            catch (Exception e)
            {
                logger.LogError(e, "修密码失败");
                throw new AuthException("修密码失败", e);
            }

            */
        }

        public IPrincipal FindUser(string account)
        {
            var user = authProvider.FindUser(account);
            if (user == null) return null;
            List<Claim> claims = new List<Claim>()
                {
                     new Claim("name",user.Name),
                     new Claim("displayName",user.DisplayName),
                     new Claim("sid",user.ID.ToString()),
                };
            if (option.Properties != null)
            {
                claims.AddRange(user.Properties.Where(n => option.Properties.Contains(n.Key) && n.Value != null).Select(n => new Claim(n.Key, n.Value.ToString())));
            }

            var identity = new ClaimsIdentity(claims, option.AuthenticationType, option.NameType, option.RoleType);
            return new ClaimsPrincipal(identity);
        }

        public bool ValidateCredentials(string account, string password)
        {

            return authProvider.ValidateCredentials(account, password);

        }
    }
}
